<template>
  <div class="w-25 mx-auto">
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button class="btn btn-primary">登录</button>
      </slot>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
import mitt from 'mitt'
type validateFunc = () => boolean
export const emitter = mitt()
export default defineComponent({
  emits: ['form-submit'],
  setup (props, context) {
    let funArr: validateFunc[] = []

    const submitForm = () => {
      const result = funArr.map((validateFunc) => validateFunc()).every((value: boolean) => {
        return value
      })
      context.emit('form-submit', result)
    }

    const callback = (validateFunc: validateFunc | undefined) => {
      if (validateFunc) {
        funArr.push(validateFunc)
      }
    }
    emitter.on('form-item-created', callback)

    onUnmounted(() => {
      emitter.off('form-item-created', callback)
      funArr = []
    })
    return {
      submitForm
    }
  }
})
</script>
